import { NETWORKS, getNetworkByChainId } from '@/src/config/networks';

export default {
  // 切换网络
  async switchNetwork(targetNetworkKey) {
    const targetNetwork = NETWORKS[targetNetworkKey];
    if (!targetNetwork) throw new Error('不支持的区块链网络');

    try {
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: targetNetwork.chainId }]
      });
      return targetNetwork;
    } catch (error) {
      if (error.code === 4902) {
        return await this.addNetwork(targetNetwork);
      }
      throw error;
    }
  },

  // 添加网络
  async addNetwork(networkConfig) {
    try {
      await window.ethereum.request({
        method: 'wallet_addEthereumChain',
        params: [networkConfig]
      });
      return networkConfig;
    } catch (error) {
      throw new Error(`添加网络失败: ${error.message}`);
    }
  },

  // 获取当前网络
  async getCurrentNetwork() {
    const chainId = await window.ethereum.request({ method: 'eth_chainId' });
    return getNetworkByChainId(chainId) || { ...NETWORKS.ETH, chainId };
  },

  // 验证是否为目标网络
  async validateNetwork(targetNetworkKey) {
    const current = await this.getCurrentNetwork();
    return current.chainId === NETWORKS[targetNetworkKey]?.chainId;
  }
};